<template>
  <div>
    <div class="router-content">
      <div v-if="pageType == 'list'">
        <div>
          <QueryBar
            :queryForm="queryForm"
            :queryConfig="queryBar"
            @handleQueryClick="handleQueryClick"
          />
          <div style="margin-bottom: 20px">
            <el-button
              icon="el-icon-plus"
              type="primary"
              @click="addList"
              v-if="add"
              >新增用户</el-button
            >
          </div>
          <el-table :data="tableData" style="width: 100%" border>
            <el-table-column type="index" label="序号" width="50">
              <template slot-scope="scope">{{
                10 > scope.$index + 1
                  ? "0" + (scope.$index + 1)
                  : scope.$index + 1
              }}</template>
            </el-table-column>
            <el-table-column prop="username" label="用户名"> </el-table-column>
            <el-table-column prop="realName" label="姓名"> </el-table-column>
            <el-table-column prop="roleName" label="所属角色">
            </el-table-column>
            <el-table-column prop="disabled" label="状态">
              <template slot-scope="scope">
                {{ scope.row.disabled ? "禁用" : "启用" }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
              <template slot-scope="scope" v-if="scope.row.createTime">
                {{ scope.row.createTime | formatTime }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div v-if="scope.row.defaulted">不可操作</div>
                <div v-else>
                  <el-tag
                    v-if="edit"
                    style="cursor: pointer; margin-right: 10px"
                    @click="handleOptions({ key: '1', index: scope.$index })"
                    size="medium"
                    >修改</el-tag
                  >
                  <el-tag
                    v-if="!scope.row.disabled && disable"
                    style="cursor: pointer"
                    @click="handleOptions({ key: '2', index: scope.$index })"
                    size="medium"
                    >禁用</el-tag
                  >
                  <el-tag
                    v-if="scope.row.disabled && enable"
                    style="cursor: pointer"
                    @click="handleOptions({ key: '3', index: scope.$index })"
                    size="medium"
                    >启用</el-tag
                  >
                  <el-tag
                    v-if="reset"
                    style="cursor: pointer; margin: 10px"
                    @click="handleOptions({ key: '4', index: scope.$index })"
                    size="medium"
                    >重置密码</el-tag
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="margin-top: 50px"
            @current-change="handlePageChange"
            :current-page="pageParams.pageNum"
            :page-sizes="[pageParams.pageSize]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="count"
          ></el-pagination>
        </div>
      </div>
      <div v-else>
        <el-form
          :model="formModel"
          :rules="formRules"
          ref="formModel"
          label-width="130px"
        >
          <div class="form-tips" v-if="showTips">
            <i class="el-icon-question"></i>
            <span>默认登陆密码为：88888888</span>
            <i class="el-icon-close" @click="showTips = false"></i>
          </div>
          <el-form-item
            label="用户名"
            style="width: 550px;22px"
            prop="username"
          >
            <el-input
              :disabled="pageType == 'edit'"
              v-model="formModel.username"
              placeholder="请输入用户名"
              maxlength="30"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item> 温馨提示：用户名不允许修改 </el-form-item> -->

          <el-form-item label="姓名" style="width: 550px;22px" prop="realName">
            <el-input
              v-model="formModel.realName"
              placeholder="请输入姓名"
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属角色" prop="roleId">
            <el-checkbox-group v-model="formModel.roleId">
              <el-checkbox
                v-for="(item, index) in roleList"
                :key="index"
                :label="item.roleId"
                >{{ item.roleName }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('formModel')"
              :loading="$store.state.subLoading"
              >确认</el-button
            >
            <el-button @click="closeForm('formModel')">关闭</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <Modal
      :title="
        modalType == 'enable'
          ? '启用提示'
          : modalType == 'disable'
          ? '禁用提示'
          : modalType == 'reset'
          ? '重置密码'
          : ''
      "
      :dialogVisible="visible"
      :loading="$store.state.subLoading"
      @handleClose="handleCancel"
      @handleConfirm="handleConfirm"
      width="600px"
    >
      <div
        v-if="modalType == 'enable'"
        style="display: flex; align-items: center"
      >
        <i
          class="el-icon-warning"
          style="color: #faad14; font-size: 18px; margin: 0 20px"
        ></i>
        确定启用该角色吗？
      </div>
      <div
        v-else-if="modalType == 'disable'"
        style="display: flex; align-items: center"
      >
        <i
          class="el-icon-warning"
          style="color: #faad14; font-size: 18px; margin: 0 20px"
        ></i>
        确定禁用该角色吗？
      </div>
      <div v-else-if="modalType == 'reset'">
        <div class="form-tips" style="width: 80%">
          <i
            class="el-icon-warning"
            style="margin-right: 15px; color: #faad14"
          ></i>
          重置密码为：88888888
        </div>
        <p>是否重置该用户密码？</p>
      </div>
    </Modal>
  </div>
</template>
<script>
import QueryBar from "@/components/common/QueryBar.vue";
import TableComponent from "@/components/common/TableComponent.vue";
import Modal from "@/components/common/Modal.vue";
import api from "@/api/modules/permissions/user.js";
import util from "@/utils";
export default {
  name: "user",
  components: { QueryBar, TableComponent, Modal },
  data() {
    return {
      add: true,
      edit: true,
      reset: true,
      enable: true,
      disable: true, //按钮权限
      pageType: "list",
      showTips: true,
      modalType: "",
      visible: false,
      queryForm: {},
      queryBar: [
        {
          label: "用户名",
          queryKey: "username",
          isInput: true,
        },
        {
          label: "姓名",
          queryKey: "realName",
          isInput: true,
        },
        {
          label: "所属角色",
          queryKey: "roleId",
          isSelect: true,
          seletOptions: [],
        },
        {
          label: "状态",
          queryKey: "disabled",
          isSelect: true,
          width: "400px",
          seletOptions: [
            {
              value: "",
              label: "全部",
            },
            {
              value: "false",
              label: "启用",
            },
            {
              value: "true",
              label: "禁用",
            },
          ],
        },
        {
          label: "创建时间",
          queryKey: "timeRange",
          isRange: true,
          width: "500px",
        },
      ],
      currentRow: "",
      tableData: [],
      count: 0,
      pageParams: {
        pageNum: 1,
        pageSize: 10,
      },
      formModel: {
        username: "", //用户名
        realName: "", // 姓名
        roleId: [],
      },
      formRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "change" },
          {
            pattern: /^[a-zA-Z][a-zA-Z0-9]{3,11}$/,
            message: "请输入以字母开头4-12位字母和数字组合的用户名，支持纯字母",
            trigger: "blur",
          },
        ],
        realName: [
          { required: true, message: "请输入姓名", trigger: "change" },
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
      roleList: [],
    };
  },
  mounted() {
    this.$nextTick(() => {
      // 设置页面按钮权限
      let btns = this.$store.state.userInfo.list[0].children[1];
      this.add = btns.children[0].havePermission;
      this.edit = btns.children[1].havePermission;
      this.enable = btns.children[2].havePermission;
      this.disable = btns.children[3].havePermission;
      this.reset = btns.children[4].havePermission;
      
      this.getData(this.pageParams);
      api.getRoleList().then((res) => {
        this.roleList = res.data;
        let list = [];
        this.roleList.forEach((item) => {
          let obj = { label: item.roleName, value: item.roleId };
          list.push(obj);
        });
        list.unshift({ label: "全部", roleId: "" });
        this.queryBar[2].seletOptions = list;
      });
    });
  },
  methods: {
    getData(params) {
      try {
        api.getUserPage(params ? params : { ...this.pageParams, ...this.queryForm }).then((res) => {
          this.tableData = res.data;
          this.count = +res.count;
          this.pageType = "list";
        });
      } catch (error) {}
    },
    handlePageChange(val) {
      this.pageParams.pageNum = val;
      this.getData({ ...this.pageParams, ...this.queryForm });
    },
    handleQueryClick(val) {
      switch (val) {
        case "search":
          this.pageParams.pageNum = 1;
          if (this.queryForm.timeRange) {
            let obj = {
              username: this.queryForm.username,
              realName: this.queryForm.realName,
              roleId: this.queryForm.roleId,
              disabled: this.queryForm.disabled,
              startTime: util.formatTime(this.queryForm.timeRange[0]),
              endTime: util.formatTime(this.queryForm.timeRange[1]),
            };
            this.getData({ ...this.pageParams, ...obj });
          } else {
            this.getData({ ...this.pageParams, ...this.queryForm });
          }
          break;
        case "reset":
          Object.keys(this.queryForm).forEach((item) => {
            this.queryForm[item] = "";
          });
          this.pageNum = 1;
          this.getData(this.pageParams);
          break;
      }
    },
    handleCancel() {
      this.visible = false;
    },
    handleConfirm() {
      this.$store.commit("setSubLoading", true);
      switch (this.modalType) {
        case "enable":
          api.enableUser({ userId: this.currentRow.userId }).then((res) => {
            this.$message.success("启用成功");
            this.visible = false;
            this.getData(this.pageParams);
          });
          break;
        case "disable":
          api.disableUser({ userId: this.currentRow.userId }).then((res) => {
            this.$message.success("禁用成功");
            this.visible = false;
            this.getData(this.pageParams);
          });
          break;
        case "reset":
          api.resetUser({ userId: this.currentRow.userId }).then((res) => {
            if (res) {
              this.$message.success("重置密码成功");
              this.visible = false;
              this.getData(this.pageParams);
            }
          });
          break;
      }
    },
    handleOptions(val) {
      const { key, index } = val;
      this.currentRow = this.tableData[index];
      switch (key) {
        case "1":
          Object.keys(this.formModel).forEach((item) => {
            this.formModel[item] = this.currentRow[item];
          });
          let list = [];
          this.roleList.forEach((item) => {
            if (this.currentRow.roleName.includes(item.roleName)) {
              list.push(item.roleId);
            }
          });

          this.formModel["roleId"] = list;
          this.pageType = "edit";
          return;
          break;
        case "2":
          this.modalType = "disable";
          this.visible = true;
          break;
        case "3":
          this.modalType = "enable";
          this.visible = true;
          break;
        case "4":
          this.modalType = "reset";
          this.visible = true;
          break;
      }
    },
    addList() {
      Object.keys(this.formModel).forEach((item) => {
        this.formModel[item] = "";
      });
      this.formModel.roleId = [];
      this.pageType = "add";
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store.commit("setSubLoading", true);
          if (this.pageType == "add") {
            api.addUser(this.formModel).then((res) => {
              this.$message.success("新增成功");
              this.pageParams.pageNum=1
              this.getData();
            });
          } else {
            api
              .modifyUser({
                realName: this.formModel.realName,
                roleId: this.formModel.roleId,
                userId: this.currentRow.userId,
              })
              .then((res) => {
                this.$message.success("编辑成功");
                this.getData();
              });
          }
        } else {
          return false;
        }
      });
    },
    closeForm(formName) {
      this.$refs[formName].resetFields();
      this.pageType = "list";
    },
  },
};
</script>
<style lang="less" scoped>
.details-page {
  h5 {
    font-size: 16px;
  }
  ul {
    width: 100%;
    li {
      float: left;
      margin-bottom: 15px;
      width: 33.3% !important;
      span {
        color: #666;
      }
    }
  }

  .basic {
    height: 150px;
    border-bottom: 1px solid #ccc;
  }
  .option {
    margin-top: 50px;
    text-align: center;
  }
  .modalContent {
    display: flex;
    align-items: center;
    .el-icon-question {
      font-size: 20px;
      margin-right: 20px;
      color: #faad14;
    }
  }
  .portal {
    > div {
      min-height: 330px;
    }
  }
}
</style>
